#-------------------------------------------------------------------------------
# Name:        module1
# Purpose:
#
# Author:      Sanchez
#
# Created:     27/06/2012
# Copyright:   (c) Sanchez 2012
# Licence:     <your licence>
#-------------------------------------------------------------------------------
import socket
import sys
import time
import threading
import struct
import numpy as np


class Survey(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)
        self.Terminated = False
    def run(self):
        while not self.Terminated:
            s="AD:STAT:SCAN?"
            rep=ScpiQuery(s)
            print  rep
            time.sleep(0.5)
    def stop(self):
        self.Terminated = True



def ScpiCommand(sCommand):
    s=sCommand+"\n"
    err=sock.sendall(s)
    return err

def ScpiQuery(sCommand):
    s=sCommand+"\n"
    err=sock.sendall(s)
    # Look for the response
    amount_received = 0
    amount_expected = 1
    while amount_received < amount_expected:
        sResponse = sock.recv(1024)
        amount_received += len(sResponse)
    return sResponse


# Create a TCP/IP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# Bind the socket to the port
server_address = ('169.254.241.19',5025)
sock.connect(server_address)

try:
    s = '*IDN?'
    rep=ScpiQuery(s)
    print  rep

    s="*RST"
    err=ScpiCommand(s)
    print  err

    s=":AD:ENAB ON,(@1,2,3,4)"
    err=ScpiCommand(s)
    print  err

    type="DC"
    s=":AD:COUP "+type+",(@1,2,3,4)"
    err=ScpiCommand(s)
    print  err

    s=":AD:BUFF:MODE wrap"
    err=ScpiCommand(s)
    print  err

    level=1
    s=":AD:GAIN "+str(level)+",(@1,2,3,4)"
    err=ScpiCommand(s)
    print  err

    s=":AD:CLOCK:SOURCE INTERNAL"
    err=ScpiCommand(s)
    print  err

    freq=5000
    s=":AD:CLOC:FREQ "+str(freq)
    err=ScpiCommand(s)
    print  err

    s = "AD:CLOCK:FREQ?"
    rep=ScpiQuery(s)
    print  rep

    s=":AD:TRIG IMM"
    err=ScpiCommand(s)
    print  err

    s=":AD:ARM"
    err=ScpiCommand(s)
    print  err

    s=":AD:INIT"
    err=ScpiCommand(s)
    print  err


    TH=Survey()
    print "debut acquisition..."
    TH.start()
    tacq=1
    time.sleep(tacq)
    TH.stop()
    s=":AD:ABORT"
    err=ScpiCommand(s)
    print  err

    print "debut acquisition..."
    nomfic="test.dat"
    fd = open(nomfic, 'wb')
    # recup donnees
    s=":AD:FETCH? 0"
    err=ScpiCommand(s)
    print  err


    # lecture du header #6,lenRecord,scanCount,numChannel,scanIndex,timeStamps,timeStampns
    amount_received = 0
    amount_expected = len(s)

    while amount_received < amount_expected:
        data = sock.recv(28)
        amount_received += len(data)
    print  data,len(data)
    fd.write(data)
    #---------------------------------------
    s=struct.unpack_from('2c',data)
    print "s=",s
    #---------------------------------------
    sizeHeader=int(s[1])  # en general 6 mais atention parfois 2
    # lecture taille du bloc de data suivant
    fmt=str(sizeHeader)+"c"    #formattage headertest.dat'
    s=struct.unpack_from(fmt,data[2:])
    print "s unpack =",s
    L=len(s)
    lenRecord=0
    for i in range(L):
        lenRecord = pow(10,i)*int(s[L-i-1]) + lenRecord
    print "lenRecord=",lenRecord
    #--------------------------------------
    offset = 0
    RawRecord=[]
    total=0
    buff=[]
    while (offset < lenRecord-28):
        RawRecord = sock.recv(lenRecord - offset)
        lenrecu=len(RawRecord)
#        print "lenrecu=",lenrecu
        total=total+lenrecu
        print "total=",total
        offset = offset + lenrecu
        print"offset=",offset
        fd.write(RawRecord)





    fd.close()
finally:
    sock.close()

